package com.guangzhi.weijianzhi.activity;

import m.framework.ui.widget.slidingmenu.SlidingMenu;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.guangzhi.weijianzhi.R;
import com.guangzhi.weijianzhi.context.WeiJianZhiEntity;
import com.guangzhi.weijianzhi.http.HttpRequestUtils;
import com.guangzhi.weijianzhi.http.MyAsyncHttpResponseHandler;
import com.guangzhi.weijianzhi.utils.Misc;
import com.guangzhi.weijianzhi.view.LodingFragmentDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.umeng.analytics.MobclickAgent;

/**
 * @author 登陆类
 */
public class LoginActivity extends BaseActivity implements OnClickListener {
	protected static SlidingMenu mSlidingMenu;
	private EditText userNameEdt, passwordEdt;
	private TextView forgetPasswordTxt, rightBtn;
	private Button loginBtn;
	private ImageView leftBtn;
	private String phoneNum;
	private boolean mExit;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loginactivity);
		mExit = getIntent().getBooleanExtra("exit", false);
		SharedPreferences sharedPreferences = getSharedPreferences("phonenumber",Context.MODE_PRIVATE);//取出上一次电话号码
		phoneNum = sharedPreferences.getString("number","");
		initView();
		onclicklistener();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	


	public void initView() {
		leftBtn = (ImageView) findViewById(R.id.goBack);
		userNameEdt = (EditText) findViewById(R.id.user_name_edt);
		
		if(Misc.notNull(phoneNum)){
			userNameEdt.setText(phoneNum);
		}
		
		passwordEdt = (EditText) findViewById(R.id.password_edt);
		loginBtn = (Button) findViewById(R.id.login_btn);
		rightBtn = (TextView) findViewById(R.id.iszhice);
		forgetPasswordTxt = (TextView) findViewById(R.id.forgetPassword);
		forgetPasswordTxt.setText(Html.fromHtml("<u>" + "忘记密码" + "</u>"));
	}

	public void onclicklistener() {
		loginBtn.setOnClickListener(this);
		leftBtn.setOnClickListener(this);
		forgetPasswordTxt.setOnClickListener(this);
		rightBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.goBack:
			finish();
			break;
		case R.id.login_btn:
			
			if (userNameEdt.getText().toString().equals("")
					|| passwordEdt.getText().toString().equals("")) {
				Toast.makeText(LoginActivity.this, "用户名及密码不能为空", Toast.LENGTH_SHORT)
						.show();
			} else {
				newLogin(userNameEdt.getText().toString(), passwordEdt.getText().toString());
			}
			break;

		case R.id.iszhice:
			Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
			intent.putExtra("flag", "reg");
			startActivity(intent);
			Misc.setActivityAnimation(LoginActivity.this);

			break;

		case R.id.forgetPassword:
			Intent forgetIntent = new Intent();
			forgetIntent.setClass(LoginActivity.this, ForgetPasswordActivity.class);
			startActivity(forgetIntent);
			break;
		}
	}

	@SuppressWarnings("static-access")
	private void newLogin(String username,String password) {
		// TODO Auto-generated method stub
		
		
		HttpRequestUtils.doHttpLogin(username, password, new MyAsyncHttpResponseHandler(getSupportFragmentManager(), getResources()) {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				super.onSuccess(arg0, arg1, arg2);
				
				try {
					JSONObject json = new JSONObject(new String(arg2));
					
					if(json.optBoolean("status")){
						JSONObject jsonObj = json.optJSONObject("data");
						dataLogin(jsonObj.optString("code"));
					}else{
						String error = json.optString("errMessage");
						Toast.makeText(LoginActivity.this, error, 0).show();
						LodingFragmentDialog.dismiss(getSupportFragmentManager());
					}
					
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			
			
		});
		
	}
	
	
	/**
	 * 登录成功返回数据
	 */
	@SuppressWarnings("static-access")
	private void dataLogin(String code ) {
		
		
		HttpRequestUtils.doHttpLoginData(code, new AsyncHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				try {
					JSONObject json = new JSONObject(new String(arg2));
					if(!json.toString().contains("error")){
						if("".equals(json.optString("userType"))){
							//说明用户没有选择身份（个人或者商户）
							Intent intent = new Intent(LoginActivity.this, UserAndCompanyActivity.class);
							intent.putExtra("token", json.optString("access_token"));
							startActivity(intent);
						}else {
							WeiJianZhiEntity.access_token =json.optString("access_token");
							WeiJianZhiEntity.userType =json.optString("userType");
						 	WeiJianZhiEntity.userPic = json.optString("avatar");
							Intent in = new Intent(LoginActivity.this,  MainPageActivity.class);
							WeiJianZhiEntity.isLogin =1;//设置为1说明要在0nresume方法中区分
							startActivity(in);
						}
						WeiJianZhiEntity.qiNiuiToken =Misc.getToken(json.optString("qiniuToken"));
						
						SharedPreferences mySharedPreferences=getSharedPreferences("phonenumber", 
								Context.MODE_PRIVATE); 
								SharedPreferences.Editor editor = mySharedPreferences.edit(); 
								editor.putString("number",userNameEdt.getText().toString()); 
								editor.commit(); 
					}
					LoginActivity.this.finish();
						
						
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				// TODO Auto-generated method stub
				try {
					JSONObject jsonObject = new JSONObject(new String(arg2));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("");
			}
			
			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				super.onFinish();
				
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
			}
			
		});
		
		
	}
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			// TODO Auto-generated method stub
			 if (keyCode == KeyEvent.KEYCODE_BACK) {
				 if(mExit){
					 Intent in = new Intent(LoginActivity.this,  MainPageActivity.class);
					 WeiJianZhiEntity.isLogin =1;
					 startActivity(in);
				 }else{
					 finish();
				 }
				 
			 }
			return super.onKeyDown(keyCode, event);
		}
}
